<template>
    <el-tabs v-model="activeName" @tab-click="handleClick" v-loading="loading">
        <el-tab-pane v-for="(res, index) in electricityData" :key="index" :label="res.name">
            <div class="monitoring-content">
                <div>
                    <div class="monitoring-title">{{ res.name }}</div>
                    <div style="margin-top: 15px">
                        <el-input placeholder="请输入内容" v-model="input3" class="input-with-select">
                            <el-button slot="append" icon="el-icon-search" @click="queryMonitoring">搜索</el-button>
                        </el-input>
                    </div>
                    <div class="monitoring-facility" v-for="(it, index) in res.children" :key="index">
                        <div class="facility-nav css-flex">
                            <div class="facility-title css-flex">
                                <div class="facility-img title-img"></div>
                                {{ it.name || '--' }} 设备号：{{ it.device_code || '--' }}
                            </div>
                            <div class="css-flex">
                                <div class="state" style="color: #1ed950" v-if="it.iot_node_status === 1">工作中</div>
                                <div class="state" v-if="it.iot_node_status === 18">未连接</div>
                                <div class="state" style="color: #1ed950" v-if="it.iot_node_status === 16">在线</div>
                                <div class="state" v-if="it.iot_node_status === 17">设备已离线</div>
                                <div v-if="it.iot_node_status === 16" class="button-state click-pointer">锁定</div>
                                <div v-if="it.iot_node_status === 1" class="button-state1 click-pointer">停止作业</div>
                            </div>
                        </div>
                        <div class="facility-place css-flex">
                            <div class="place css-flex">
                                <div class="facility-img place-img"></div>
                                位置：{{ it.lonLat || '--' }}
                            </div>
                            <div class="place-content css-flex click-pointer" @click="goDetails(it, 'place')">
                                <div class="place-time">{{ it.mtime || '--' }}</div>
                                详情
                                <div class="monitoring-arrows"></div>
                            </div>
                        </div>
                        <div class="facility-place css-flex">
                            <div class="css-flex">
                                <div class="facility-img place-img"></div>
                                图片
                            </div>
                            <div class="img-content place-content css-flex click-pointer" @click="goDetails(it, 'img')">
                                详情
                                <div class="monitoring-arrows"></div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- <button @click="startPolling">anniusdsd</button> -->
                <el-pagination
                    :current-page.sync="currentPage"
                    background
                    layout="prev, pager, next"
                    :total="paging"
                    @current-change="onClickPaging"
                />
            </div>
        </el-tab-pane>
    </el-tabs>
    <!-- <div class="right-icon click-pointer" @click="handleRightBtn"></div> -->
</template>

<script>
import {facilityData, facilityTab} from '@/utils/api.js';
export default {
    name: 'electricity',
    props: {},
    data() {
        return {
            electricityData: [],
            activeName: '0',
            tabActive: {},
            input3: '',
            paging: 0,
            loading: true,
            tabId: {},
            currentPage: 1,
            titleData: [],
            pagination: 1,
            contrast: [],
        };
    },
    computed: {},
    watch: {
        // electricityData(newVal) {
        //     if(newVal){
        //         console.log('electricityData changed:', newVal);
        //         this.facilityTabA();
        //     }
        // },
    },
    methods: {
        handleLeftBtn() {
            if (Number(this.active) <= 1) {
                this.active = '1';
            } else {
                this.active = Number(this.active) - 1 + '';
                this.activeName = this.unit.find(item => item.indexId == this.active).name;
                this.params.scene_id = this.unit.find(item => item.indexId == this.active).id;
                this.getEquipment(this.params);
            }
        },
        handleRightBtn() {
            if (Number(this.active) >= this.unit.length) {
                this.active = Number(this.unit.length) + '';
            } else {
                this.active = Number(this.active) + 1 + '';
                this.activeName = this.unit.find(item => item.indexId == this.active).name;
                this.params.scene_id = this.unit.find(item => item.indexId == this.active).id;
                this.getEquipment(this.params);
            }
        },
        goDetails(res, item) {
            this.$emit('goDetails', {res, item});
        },
        //切换tab
        handleClick(tab) {
            this.tabId = {};
            this.loading = true;
            this.pagination = 1;
            this.tabId = this.electricityData.find(it => it.name === tab._props.label);
            // Header received, request content interface
            facilityData(this.tabId.id, 1, 3)
                .then(res => {
                    if (res && res.data) {
                        this.tabId.children = res.data.data || [];
                        this.paging = res.data.totalPage * 10;
                    } else {
                        this.tabId.children = [];
                        this.paging = 0;
                    }
                    this.loading = false;
                })
                .catch(() => {
                    this.tabId.children = [];
                    this.loading = false;
                });
        },
        //切换页数
        onClickPaging(val) {
            this.loading = true;
            this.pagination = val;
            facilityData(this.tabId.id, this.pagination, 3, this.input3)
                .then(res => {
                    if (res && res.data) {
                        this.electricityData.find(it => it.name === this.tabId.name).children = res.data.data || [];
                        this.tabId.children = res.data.data || [];
                    } else {
                        this.electricityData.find(it => it.name === this.tabId.name).children = [];
                        this.tabId.children = [];
                    }
                    this.loading = false;
                })
                .catch(() => {
                    this.electricityData.find(it => it.name === this.tabId.name).children = [];
                    this.tabId.children = [];
                    this.loading = false;
                });
        },
        //搜索
        queryMonitoring() {
            this.loading = true;
            facilityData(this.electricityData[0]?.id, 1, 3, this.input3)
                .then(res => {
                    if (res && res.data) {
                        this.electricityData[0].children = res.data.data || [];
                        this.paging = res.data.totalPage * 10;
                        this.tabId = this.electricityData[0]; // Default tabId
                    } else {
                        this.electricityData[0].children = [];
                        this.paging = 0;
                        this.tabId = this.electricityData[0];
                    }
                    this.loading = false;
                })
                .catch(() => {
                    this.electricityData[0].children = [];
                    this.loading = false;
                });
        },
        async facilityTabA() {
            this.loading = true; // 开始加载
            this.currentPage = 1;
            try {
                if (this.titleData.length === 0) {
                    // Fetch header data
                    const res = await facilityTab(5000);
                    this.titleData = res.data?.data || [];
                }
                // Process unique names
                const uniqueNames = new Set();
                this.electricityData = this.titleData
                    .map(({name, id}) => ({name, id}))
                    .filter(({name}) => {
                        if (uniqueNames.has(name)) return false;
                        uniqueNames.add(name);
                        return true;
                    });
                // Update store and tab state
                const names = this.titleData.map(({name}) => name);
                this.$store.dispatch('moveShow', names);
                this.tabActive = this.titleData.reduce((acc, {name}, index) => {
                    acc[name] = String(index);
                    return acc;
                }, {});
                this.activeName = this.tabActive[this.$route.query?.val?.name] || '0';
                const id = this.$route.query?.val?.id || this.electricityData[0]?.id;
                const contentRes = await facilityData(id, 1, 3);
                const contentData = contentRes.data?.data || [];
                const queryVal = this.$route.query?.val?.name;
                const content = this.electricityData.find(it => it.name === queryVal);
                if (content) {
                    this.$set(content, 'children', contentData);
                } else if (this.electricityData.length > 0) {
                    this.$set(this.electricityData[0], 'children', contentData);
                }
                this.paging = contentRes.data?.totalPage * 10 || 0;
                this.tabId = this.electricityData[0]; // Default tabId
            } catch (error) {
                this.$message.error('获取数据失败');
            } finally {
                this.loading = false; // 结束加载
            }
        },
        async startPolling() {
            // 查找当前 tabId 对应的对象
            const currentContrast = this.electricityData.find(it => it.id === this.tabId.id);
            if (!currentContrast) {
                console.error('未找到对应的 tabId');
                return;
            }
            try {
                const res = await facilityData(this.tabId.id, this.pagination, 3, this.input3);
                // 确保 res.data?.data 是有效的数组
                currentContrast.children = Array.isArray(res.data?.data) ? [...res.data.data] : [];
                this.paging = res.data.totalPage * 10;

                // 处理 currentContrast 的其他属性
                // currentContrast.children[0].iot_node_status = 1;
                // currentContrast.children[0].name = '小明';
                this.$forceUpdate();
            } catch (error) {
                console.log('获取数据失败', error);
            }
        },
    },
    activated() {
        this.paging = 10;
        this.facilityTabA();
        setInterval(() => this.startPolling(), 3000);
    },
};
</script>

<style scoped>
.monitoring-content >>> .el-pager li {
    background: rgba(4, 44, 91, 0.02);
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #0e5fff;
}

.monitoring-content >>> .btn-next {
    background: rgba(4, 44, 91, 0.02);
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #0e5fff;
}

.monitoring-content >>> .el-pagination {
    margin-bottom: 10px;
}

.monitoring-content >>> .btn-prev {
    background: rgba(4, 44, 91, 0.02);
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #0e5fff;
}

.monitoring-arrows {
    background-image: url('@/assets/img/monitoring-arrows.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 20px;
    height: 20px;
}

.place-content {
    color: #8ab5eb;
}

.place-time {
    margin-right: 15px;
}

.state {
    color: #ff3e3e;
}

.facility-place {
    border: 1px solid rgba(0, 170, 255, 0.5);
    padding: 0 10px;
    background: rgba(0, 170, 255, 0.08);
    color: #d3d4dd;
}

.place-img {
    background-image: url('@/assets/img/place-img.png');
}

/* 组件样式 */
.monitoring-content {
    background-image: url('@/assets/img/atlas-message.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 100%;
    padding: 0 20px;
    flex: 1;
    overflow: hidden;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.monitoring-content >>> .el-input-group__append {
    background: none;
    border: #0177fd 1px solid;
    background-color: #0177fd;
    color: #fff;
}

.monitoring-content >>> [class^='el-icon-'] {
    display: inline-block !important;
    width: auto !important;
    height: auto !important;
    background: none !important;
}

.monitoring-content >>> .el-input__inner {
    background: none;
    border: #0177fd 1px solid;
}

.monitoring-title {
    font-size: 14px;
    color: #19ecff;
    line-height: 20px;
    text-align: center;
    font-weight: bold;
}

.input-with-select .el-input-group__prepend {
    background-color: #fff;
}

.monitoring-facility {
    line-height: 38px;
    font-size: 14px;
    margin-top: 10px;
}

.facility-nav {
    border: 1px solid rgba(0, 170, 255, 0.5);
    background: #0d3e9e;
    padding: 0 10px;
}

.facility-title {
    font-weight: bold;
    color: #ffffff;
}

.facility-img {
    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 20px;
    height: 20px;
    margin-right: 10px;
}

.title-img {
    background-image: url('@/assets/img/title-img.png');
}

.button-state {
    background: linear-gradient(270deg, #0047ff 0%, #059acb 100%);
    border-radius: 4px 4px 4px 4px;
    width: 50px;
    text-align: center;
    line-height: 30px;
    margin-left: 10px;
    color: #fff;
    font-size: 14px;
    font-weight: 400;
}
.left-icon {
    background-image: url('@/assets/img/jt-left.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 42px;
    height: 42px;
}
.right-icon {
    background-image: url('@/assets/img/jt-right.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
    width: 42px;
    height: 42px;
}

.button-state1 {
    background: linear-gradient(90deg, #ffb20d 0%, #ff5e0d 100%);
    border-radius: 4px 4px 4px 4px;
    width: 80px;
    text-align: center;
    line-height: 30px;
    margin-left: 10px;
    color: #fff;
    font-size: 14px;
    font-weight: 400;
    flex-shrink: 0;
}
</style>
